package com.example.figurehecheng.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.figurehecheng.common.constant.JwtClaimsConstant;
import com.example.figurehecheng.common.constant.MessageConstant;
import com.example.figurehecheng.common.properties.JwtProperties;
import com.example.figurehecheng.common.utils.JwtUtil;
import com.example.figurehecheng.domain.dto.MerchantLoginDTO;
import com.example.figurehecheng.domain.entity.Merchant;
import com.example.figurehecheng.mapper.MerchantMapper;
import com.example.figurehecheng.service.IMerchantService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 商家表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-04
 */
@Service
@RequiredArgsConstructor
public class MerchantServiceImpl extends ServiceImpl<MerchantMapper, Merchant> implements IMerchantService {

    private final JwtProperties jwtProperties;

    /**
     * 商家登录
     * @param merchantLoginDTO 登录信息
     * @return
     */
    @Override
    public Map<String, Object> login(MerchantLoginDTO merchantLoginDTO) {
        // 1. 根据用户名查询商家
        Merchant merchant = lambdaQuery()
                .eq(Merchant::getUsername, merchantLoginDTO.getUsername())
                .one();

        // 2. 判断商家是否存在
        if (merchant == null) {
            throw new RuntimeException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 3. 密码比对
        if (!merchant.getPassword().equals(merchantLoginDTO.getPassword())) {
            throw new RuntimeException(MessageConstant.PASSWORD_ERROR);
        }

        // 4. 检查账号状态
        if (merchant.getStatus() != 1) {
            throw new RuntimeException(MessageConstant.ACCOUNT_LOCKED);
        }
        System.out.println(merchant.getId());
        // 5. 生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, merchant.getId());
        claims.put("username", merchant.getUsername());
        String token = JwtUtil.createJWT(
            jwtProperties.getAdminSecretKey(),
            jwtProperties.getAdminTtl(),
            claims
        );

        // 6. 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("merchant", merchant);

        return result;
    }
}
